import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../models/wiki_config.dart';

/// 远程配置服务
/// Remote configuration service
class RemoteConfigService {
  static const String _configUrl =
      'https://gitee.com/ymoran/wallpaper/raw/master/game.json';
  static const String _cacheKey = 'cached_wiki_config';
  static const String _lastUpdateKey = 'config_last_update';
  static const Duration _cacheExpiry = Duration(hours: 6);

  SharedPreferences? _prefs;
  WikiConfig? _cachedConfig;

  /// 初始化服务
  Future<void> initialize() async {
    _prefs = await SharedPreferences.getInstance();
    await _loadCachedConfig();
  }

  /// 获取Wiki配置
  Future<WikiConfig> getWikiConfig({bool forceRefresh = false}) async {
    // 强制刷新或缓存过期时，清除缓存并从远程获取
    if (forceRefresh || _cachedConfig == null || _isCacheExpired()) {
      // 清除旧缓存
      if (_prefs != null) {
        await _prefs!.remove(_cacheKey);
        await _prefs!.remove(_lastUpdateKey);
      }
      _cachedConfig = null;
    }

    // 如果有缓存且未过期，直接返回缓存
    if (!forceRefresh && _cachedConfig != null && !_isCacheExpired()) {
      print('Using cached remote configuration');
      return _cachedConfig!;
    }

    try {
      // 尝试从远程获取
      final config = await _fetchRemoteConfig();
      await _cacheConfig(config);
      _cachedConfig = config;
      print('Successfully fetched remote configuration');
      return config;
    } catch (e) {
      print('Remote config fetch failed: $e');
      // 远程获取失败，返回缓存或默认配置
      if (_cachedConfig != null) {
        print('Using expired cached configuration as fallback');
        return _cachedConfig!;
      }
      print('No cache available, using default remote configuration');
      return _getDefaultConfig();
    }
  }

  /// 清除缓存配置
  /// Clear cached configuration
  Future<void> clearCache() async {
    if (_prefs != null) {
      await _prefs!.remove(_cacheKey);
      await _prefs!.remove(_lastUpdateKey);
    }
    _cachedConfig = null;
    print('Cache cleared successfully');
  }

  /// 从远程获取配置
  Future<WikiConfig> _fetchRemoteConfig() async {
    try {
      final response = await http.get(
        Uri.parse(_configUrl),
        headers: {
          'Accept': 'application/json',
          'User-Agent': 'GameWiki-Pro/2.0.0',
        },
      ).timeout(const Duration(seconds: 10));

      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        return WikiConfig.fromJson(jsonData);
      } else {
        throw Exception(
            'HTTP ${response.statusCode}: Failed to load remote config');
      }
    } catch (e) {
      print('Error fetching remote config from $_configUrl: $e');
      rethrow;
    }
  }

  /// 加载缓存的配置
  Future<void> _loadCachedConfig() async {
    if (_prefs == null) return;

    final cachedJson = _prefs!.getString(_cacheKey);
    if (cachedJson != null) {
      try {
        final jsonData = json.decode(cachedJson);
        _cachedConfig = WikiConfig.fromJson(jsonData);
      } catch (e) {
        // 缓存损坏，清除
        await _prefs!.remove(_cacheKey);
        await _prefs!.remove(_lastUpdateKey);
      }
    }
  }

  /// 缓存配置
  Future<void> _cacheConfig(WikiConfig config) async {
    if (_prefs == null) return;

    final jsonString = json.encode(config.toJson());
    await _prefs!.setString(_cacheKey, jsonString);
    await _prefs!.setInt(_lastUpdateKey, DateTime.now().millisecondsSinceEpoch);
  }

  /// 检查缓存是否过期
  bool _isCacheExpired() {
    if (_prefs == null) return true;

    final lastUpdate = _prefs!.getInt(_lastUpdateKey);
    if (lastUpdate == null) return true;

    final lastUpdateTime = DateTime.fromMillisecondsSinceEpoch(lastUpdate);
    return DateTime.now().difference(lastUpdateTime) > _cacheExpiry;
  }

  /// 获取默认配置
  WikiConfig _getDefaultConfig() {
    return WikiConfig(
      version: '1.0.0',
      lastUpdated: DateTime.now(),
      wikis: [
        WikiItem(
          id: 'minecraft',
          name: 'Minecraft Wiki',
          nameEn: 'Minecraft Wiki',
          nameCn: 'Minecraft 中文Wiki',
          description: 'Official Minecraft Wiki',
          descriptionCn: '官方Minecraft百科',
          url: 'https://minecraft.wiki/',
          urlCn: 'https://zh.minecraft.wiki/',
          icon: 'https://minecraft.wiki/images/d/dd/Minecraft_Wiki.png',
          category: 'sandbox',
          tags: ['sandbox', 'building', 'survival'],
          isPopular: true,
          isOfficial: true,
          language: ['en', 'zh'],
          rating: 4.9,
          lastUpdated: DateTime.now(),
        ),
        WikiItem(
          id: 'terraria',
          name: 'Terraria Wiki',
          nameEn: 'Terraria Wiki',
          nameCn: 'Terraria 中文Wiki',
          description: 'Official Terraria Wiki',
          descriptionCn: '官方Terraria百科',
          url: 'https://terraria.wiki.gg/',
          urlCn: 'https://terraria.wiki.gg/zh/',
          icon: 'https://terraria.wiki.gg/images/d/d0/Terraria_Wiki.png',
          category: 'sandbox',
          tags: ['sandbox', 'adventure', '2d'],
          isPopular: true,
          isOfficial: true,
          language: ['en', 'zh'],
          rating: 4.8,
          lastUpdated: DateTime.now(),
        ),
        WikiItem(
          id: 'genshin',
          name: 'Genshin Impact Wiki',
          nameEn: 'Genshin Impact Wiki',
          nameCn: '原神Wiki',
          description: 'Comprehensive Genshin Impact guide',
          descriptionCn: '全面的原神攻略指南',
          url: 'https://genshin-impact.fandom.com/',
          urlCn: 'https://wiki.biligame.com/ys/',
          icon:
              'https://static.wikia.nocookie.net/gensin-impact/images/6/6b/Site-logo.png',
          category: 'rpg',
          tags: ['rpg', 'gacha', 'open-world'],
          isPopular: true,
          isOfficial: false,
          language: ['en', 'zh'],
          rating: 4.7,
          lastUpdated: DateTime.now(),
        ),
        WikiItem(
          id: 'lol',
          name: 'League of Legends Wiki',
          nameEn: 'League of Legends Wiki',
          nameCn: '英雄联盟Wiki',
          description: 'Complete League of Legends database',
          descriptionCn: '完整的英雄联盟数据库',
          url: 'https://leagueoflegends.fandom.com/',
          urlCn: 'https://lol.fandom.com/zh/',
          icon:
              'https://static.wikia.nocookie.net/leagueoflegends/images/1/12/LoL_icon.png',
          category: 'moba',
          tags: ['moba', 'competitive', 'strategy'],
          isPopular: true,
          isOfficial: false,
          language: ['en', 'zh'],
          rating: 4.6,
          lastUpdated: DateTime.now(),
        ),
        WikiItem(
          id: 'pokemon',
          name: 'Pokémon Wiki',
          nameEn: 'Pokémon Wiki',
          nameCn: '宝可梦Wiki',
          description: 'Everything about Pokémon',
          descriptionCn: '关于宝可梦的一切',
          url: 'https://pokemon.fandom.com/',
          urlCn: 'https://wiki.52poke.com/',
          icon:
              'https://static.wikia.nocookie.net/pokemon/images/4/4a/Pok%C3%A9mon_Wiki.png',
          category: 'rpg',
          tags: ['rpg', 'collection', 'adventure'],
          isPopular: true,
          isOfficial: false,
          language: ['en', 'zh'],
          rating: 4.8,
          lastUpdated: DateTime.now(),
        ),
      ],
      categories: [
        WikiCategory(
          id: 'sandbox',
          name: 'Sandbox Games',
          nameCn: '沙盒游戏',
          description: 'Creative and building games',
          descriptionCn: '创造和建造类游戏',
          icon: 'https://example.com/icons/sandbox.png',
          color: '#4CAF50',
        ),
        WikiCategory(
          id: 'rpg',
          name: 'Role Playing Games',
          nameCn: '角色扮演游戏',
          description: 'Character progression and story-driven games',
          descriptionCn: '角色成长和剧情驱动的游戏',
          icon: 'https://example.com/icons/rpg.png',
          color: '#9C27B0',
        ),
        WikiCategory(
          id: 'moba',
          name: 'MOBA Games',
          nameCn: 'MOBA游戏',
          description: 'Multiplayer online battle arena games',
          descriptionCn: '多人在线战术竞技游戏',
          icon: 'https://example.com/icons/moba.png',
          color: '#FF5722',
        ),
      ],
      features: WikiFeatures(
        searchEnabled: true,
        favoritesEnabled: true,
        historyEnabled: true,
        offlineEnabled: false,
        darkModeEnabled: true,
        multiLanguageEnabled: true,
      ),
    );
  }

  // /// 清除缓存
  // Future<void> clearCache() async {
  //   if (_prefs == null) return;

  //   await _prefs!.remove(_cacheKey);
  //   await _prefs!.remove(_lastUpdateKey);
  //   _cachedConfig = null;
  // }

  /// 获取缓存状态
  Map<String, dynamic> getCacheStatus() {
    if (_prefs == null) {
      return {
        'hasCachedData': false,
        'lastUpdate': null,
        'isExpired': true,
      };
    }

    final lastUpdate = _prefs!.getInt(_lastUpdateKey);
    return {
      'hasCachedData': _cachedConfig != null,
      'lastUpdate': lastUpdate != null
          ? DateTime.fromMillisecondsSinceEpoch(lastUpdate)
          : null,
      'isExpired': _isCacheExpired(),
    };
  }
}
